package com.xuecheng.manage_media_process.mq;

import com.alibaba.fastjson.JSON;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyun.vod20170321.models.GetPlayInfoRequest;
import com.aliyun.vod20170321.models.GetPlayInfoResponse;
import com.xuecheng.framework.domain.media.MediaFile;
import com.xuecheng.framework.domain.media.MediaFileProcess_m3u8;
import com.xuecheng.framework.utils.HlsVideoUtil;
import com.xuecheng.framework.utils.Mp4VideoUtil;
import com.xuecheng.manage_media_process.dao.MediaFileRepository;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author Administrator
 * @version 1.0
 **/
@Component
public class MediaProcessTask {

    @Value("${xc-service-manage-media.ffmpeg-path}")
    String ffmpeg_path;

    //上传文件根目录
    @Value("${xc-service-manage-media.video-location}")
    String serverPath;

    @Autowired
    MediaFileRepository mediaFileRepository;

    //接收视频处理消息进行视频处理
    @RabbitListener(queues="${xc-service-manage-media.mq.queue-media-video-processor}",containerFactory = "customContainerFactory")
    public void receiveMediaProcessTask(String msg) throws Exception {
        //1、解析消息内容，得到mediaId
        Map map = JSON.parseObject(msg, Map.class);
        String mediaId = (String) map.get("mediaId");
        //2、拿mediaId从数据库查询文件信息
        Optional<MediaFile> optional = mediaFileRepository.findById(mediaId);
        if(!optional.isPresent()){
            return ;
        }
        MediaFile mediaFile = optional.get();
        //文件类型
        String fileType = mediaFile.getFileType();
        if(!fileType.equals("avi")){
            mediaFile.setProcessStatus("303004");//无需处理
            mediaFileRepository.save(mediaFile);
            return ;
        }else{
            //需要处理
            mediaFile.setProcessStatus("303001");//处理中
            mediaFileRepository.save(mediaFile);
        }
        //3、使用工具类将avi文件生成mp4
        //String ffmpeg_path, String video_path, String mp4_name, String mp4folder_path
        //要处理的视频文件的路径
        String video_path = serverPath + mediaFile.getFilePath() + mediaFile.getFileName();
        //生成的mp4的文件名称
        String mp4_name = mediaFile.getFileId() + ".mp4";
        //生成的mp4所在的路径
        String mp4folder_path = serverPath + mediaFile.getFilePath();
        //创建工具类对象
        Mp4VideoUtil mp4VideoUtil =new Mp4VideoUtil(ffmpeg_path,video_path,mp4_name,mp4folder_path);
        //进行处理
        String result = mp4VideoUtil.generateMp4();
        if(result == null || !result.equals("success")){
            //处理失败
            mediaFile.setProcessStatus("303003");
            //定义mediaFileProcess_m3u8
            MediaFileProcess_m3u8 mediaFileProcess_m3u8 = new MediaFileProcess_m3u8();
            //记录失败原因
            mediaFileProcess_m3u8.setErrormsg(result);
            mediaFile.setMediaFileProcess_m3u8(mediaFileProcess_m3u8);
            mediaFileRepository.save(mediaFile);
            return ;
        }
        //mp4视频文件路径
        String mp4_video_path = serverPath + mediaFile.getFilePath() + mp4_name;

//        //4、将mp4生成m3u8和ts文件
//        //String ffmpeg_path, String video_path, String m3u8_name,String m3u8folder_path
//        //mp4视频文件路径
//        String mp4_video_path = serverPath + mediaFile.getFilePath() + mp4_name;
//        //m3u8_name文件名称
//        String m3u8_name = mediaFile.getFileId() +".m3u8";
//        //m3u8文件所在目录
//        String m3u8folder_path = serverPath + mediaFile.getFilePath() + "hls/";
//        HlsVideoUtil hlsVideoUtil = new HlsVideoUtil(ffmpeg_path,mp4_video_path,m3u8_name,m3u8folder_path);
//        //生成m3u8和ts文件
//        String tsResult = hlsVideoUtil.generateM3u8();
//        if(tsResult == null || !tsResult.equals("success")){
//            //处理失败
//            mediaFile.setProcessStatus("303003");
//            //定义mediaFileProcess_m3u8
//            MediaFileProcess_m3u8 mediaFileProcess_m3u8 = new MediaFileProcess_m3u8();
//            //记录失败原因
//            mediaFileProcess_m3u8.setErrormsg(result);
//            mediaFile.setMediaFileProcess_m3u8(mediaFileProcess_m3u8);
//            mediaFileRepository.save(mediaFile);
//            return ;
//        }
//        //处理成功
//        //获取ts文件列表
//        List<String> ts_list = hlsVideoUtil.get_ts_list();
//
//        mediaFile.setProcessStatus("303002");
//        //定义mediaFileProcess_m3u8
//        MediaFileProcess_m3u8 mediaFileProcess_m3u8 = new MediaFileProcess_m3u8();
//        mediaFileProcess_m3u8.setTslist(ts_list);
//        mediaFile.setMediaFileProcess_m3u8(mediaFileProcess_m3u8);
//
//        //保存fileUrl（此url就是视频播放的相对路径）
//        String fileUrl =mediaFile.getFilePath() + "hls/"+m3u8_name;
        String ACCESS_KEY_ID = "LTAI5tGrqLfbTGBAUGmgSmRt";
        String ACCESS_KEY_SECRET = "MzcJzZR2ZDMGnLgYvJxDByjnIGCvAC";
        String title = "test";
        final String videoId = testUploadVideo(ACCESS_KEY_ID, ACCESS_KEY_SECRET, title, mp4_video_path);
        com.aliyun.vod20170321.Client client = createClient("LTAI5tGrqLfbTGBAUGmgSmRt", "MzcJzZR2ZDMGnLgYvJxDByjnIGCvAC");
        GetPlayInfoRequest getPlayInfoRequest = new GetPlayInfoRequest()
                .setVideoId(videoId);
        // 复制代码运行请自行打印 API 的返回值
        GetPlayInfoResponse playInfo = client.getPlayInfo(getPlayInfoRequest);
        String fileUrl = playInfo.body.playInfoList.playInfo.get(0).getPlayURL();;
        System.out.println(fileUrl);
        mediaFile.setFileUrl(fileUrl);
        mediaFile.setProcessStatus("303002");
        mediaFileRepository.save(mediaFile);
    }

    private static String testUploadVideo(String accessKeyId, String accessKeySecret, String title, String fileName) {
        UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
        /* 可指定分片上传时每个分片的大小，默认为2M字节 */
        request.setPartSize(2 * 1024 * 1024L);
        /* 可指定分片上传时的并发线程数，默认为1，(注：该配置会占用服务器CPU资源，需根据服务器情况指定）*/
        request.setTaskNum(1);
        /* 是否开启断点续传, 默认断点续传功能关闭。当网络不稳定或者程序崩溃时，再次发起相同上传请求，可以继续未完成的上传任务，适用于超时3000秒仍不能上传完成的大文件。
        注意: 断点续传开启后，会在上传过程中将上传位置写入本地磁盘文件，影响文件上传速度，请您根据实际情况选择是否开启*/
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadVideoResponse response = uploader.uploadVideo(request);
        String videoId = response.getVideoId();
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
        } else {
            /* 如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 */
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
        return videoId;
    }

    public static com.aliyun.vod20170321.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "vod.cn-shanghai.aliyuncs.com";
        return new com.aliyun.vod20170321.Client(config);
    }
}
